package kyssion.leetcode.num1_50;

import kyssion.leetcode.util.ListNode;

public class code19_删除链表的倒数第N个节点 {
    public static void main(String[] args) {
        ListNode listNode = ListNode.createListNode(new int[]{
                1, 2, 3, 4, 5, 6, 7, 8
        });
        ListNode listNode1 = new code19_删除链表的倒数第N个节点().removeNthFromEnd(listNode, -1);
        ListNode.showListNode(listNode1);
    }

    /**
     * 方法其实有很多
     * 1. 转化成双向列表
     * 2. 生成对应的位置数组,进行删除
     * 3. 使用标记数字,动态记录倒数第几个对应的位置的方法,动态修改倒数第几个的位置
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (n <= 0) {
            return head;
        }
        ListNode newNode = new ListNode(-1);
        newNode.next = head;
        ListNode nowNode = newNode;
        ListNode deleteNode = newNode;
        int index = 0;
        while (nowNode.next != null) {
            if (index > n - 1) {
                deleteNode = deleteNode.next;
            }
            index++;
            nowNode = nowNode.next;
        }
        if (deleteNode.next != null && index >= n - 1) {
            deleteNode.next = deleteNode.next.next;
        }
        return newNode.next;
    }
}
